//
//  ViewController.m
//  02-NSURLSessionDownloadTask
//
//  Created by JamesZY on 15/8/30.
//  Copyright (c) 2015年 JamesZY. All rights reserved.
//

#import "ViewController.h"
#import "NSString+ZY.h"

@interface ViewController ()<NSURLSessionDownloadDelegate>

/** 进度条*/
@property (nonatomic,strong) UIProgressView *progressView;

/** task*/
@property (nonatomic,strong)  NSURLSessionDownloadTask *task;

/** 断点下载*/
@property (nonatomic,strong) NSData *resumeData;

/** session*/
@property (nonatomic,strong) NSURLSession *session;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 进度条
    self.progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 0, 300, 20)];
    self.progressView.center = self.view.center;
    self.progressView.progress = 0;
    [self.view addSubview:self.progressView];
    
    // 开始按钮
    UIButton *startButton = [[UIButton alloc] init];
    startButton .frame = CGRectMake(20, 100, 70, 40);
    [startButton setTitle:@"开始" forState:UIControlStateNormal];
    [startButton setBackgroundColor:[UIColor greenColor]];
    [startButton setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted];
    [self.view addSubview:startButton];
    [startButton addTarget:self action:@selector(startDownload:) forControlEvents:UIControlEventTouchDown];
    
    // 暂停按钮
    UIButton *pauseButton = [[UIButton alloc] init];
    pauseButton .frame = CGRectMake(110, 100, 70, 40);
    [pauseButton setTitle:@"暂停" forState:UIControlStateNormal];
    [pauseButton setBackgroundColor:[UIColor purpleColor]];
    [pauseButton setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted];
    [self.view addSubview:pauseButton];
    [pauseButton addTarget:self action:@selector(pauseDownload:) forControlEvents:UIControlEventTouchDown];
    
    // 继续按钮
    UIButton *proceedButton = [[UIButton alloc] init];
    proceedButton .frame = CGRectMake(200, 100, 70, 40);
    [proceedButton setTitle:@"继续" forState:UIControlStateNormal];
    [proceedButton setBackgroundColor:[UIColor orangeColor]];
    [proceedButton setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted];
    [self.view addSubview:proceedButton];
    [proceedButton addTarget:self action:@selector(proceedDownload:) forControlEvents:UIControlEventTouchDown];
    
    // 取消按钮
    UIButton *cancelButton = [[UIButton alloc] init];
    cancelButton .frame = CGRectMake(290, 100, 70, 40);
    [cancelButton setTitle:@"取消" forState:UIControlStateNormal];
    [cancelButton setBackgroundColor:[UIColor redColor]];
    [cancelButton setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted];
    [self.view addSubview:cancelButton];
    [cancelButton addTarget:self action:@selector(cancelDownload:) forControlEvents:UIControlEventTouchDown];
    
}

#pragma mark - 手势监听
// 开始下载
- (void)startDownload:(UIButton *)sender{

    NSLog(@"开始");
    [self downloadTaskProgress];
}

// 暂停下载
- (void)pauseDownload:(UIButton *)sender{

    NSLog(@"暂停");
//    [self.task suspend];
    // 如果调用cancelByProducingResumeData:方法,方法内部会回调一个block,在block中会将resumeData传递回来
    // resumeData中保存了当前下载任务的配置信息(下载到什么地方,从什么地方恢复等等)
    [self.task cancelByProducingResumeData:^(NSData *resumeData) {
        self.resumeData = resumeData;
    }];
}

// 继续下载
- (void)proceedDownload:(UIButton *)sender{

    NSLog(@"继续");
    self.task = [self.session downloadTaskWithResumeData:self.resumeData];
    [self.task resume];
}

// 取消下载
- (void)cancelDownload:(UIButton *)sender{

    NSLog(@"取消");
    [self.task cancel];
}

#pragma mark - 下载方法
- (void)downloadTask{

    // 1.创建NSURLSession
    NSURLSession *session = [NSURLSession sharedSession];
    
    NSString *str = [@"http://120.25.226.186:32812/resources/videos/minion_02.mp4" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:str];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    // 2.利用NSURLSession创建Task
    NSURLSessionDownloadTask *task = [session downloadTaskWithRequest:request completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
        NSLog(@"%@",location);
        
        // suggestedFilename获取下载的文件名
        NSString *toPath = [response.suggestedFilename cacheDir];
        
        NSLog(@"toPath = %@",toPath);
        NSURL *toPathURL = [NSURL fileURLWithPath:toPath];
        // 将下载好的文件移动到可靠位置 caches
        NSFileManager *manger = [NSFileManager defaultManager];
        [manger moveItemAtURL:location toURL:toPathURL error:nil];
    }];
    
    // 3.执行Task
    [task resume];
}

- (void)downloadTaskProgress{

    // 1.创建NSURLSession
    // configuration:session的配置信息
    // delegate:代理
    // delegateQueue:代理在哪个线程中执行
    self.session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    
    NSString *str = [@"http://120.25.226.186:32812/resources/videos/minion_02.mp4" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:str];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    // 2.利用NSURLSession创建Task
    self.task = [self.session downloadTaskWithRequest:request];
    
    // 3.执行Task
    [self.task resume];
}

#pragma mark - NSURLSessionDownloadDelegate
// 接收到服务器返回数据时调用
// 该方法会调用一次或多次
// didWriteData:此次接收数据的大小
// totalBytesWritten:总共接收到的数据大小
// totalBytesExpectedToWrite:服务器总共返回文件的大小
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
      didWriteData:(int64_t)bytesWritten
 totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{

    NSLog(@"%zd %zd %zd",bytesWritten,totalBytesWritten,totalBytesExpectedToWrite);
    self.progressView.progress = 1.0 * totalBytesWritten / totalBytesExpectedToWrite;
}

// 写入完成时调用
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location{
    
    NSString *toPath = [@"minion_02.mp4" cacheDir];
    NSURL *toPathURL = [NSURL fileURLWithPath:toPath];
    NSFileManager *manager = [NSFileManager defaultManager];
    [manager moveItemAtURL:location toURL:toPathURL error:nil];

    NSLog(@"didFinishDownloadingToURL");
    NSLog(@"%@",location);
}

// 恢复下载时调用
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
 didResumeAtOffset:(int64_t)fileOffset
expectedTotalBytes:(int64_t)expectedTotalBytes{

    NSLog(@"didResumeAtOffset");
}

// 请求完成和出现错误都会调用
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{
    
    NSLog(@"didCompleteWithError");
}

@end
